package com.info33.platform.system.dic.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.info33.platform.system.dic.dao.SysDicModDao;
import com.info33.platform.system.dic.dto.SysDicModDTO;
import com.info33.platform.system.dic.entity.SysDicMod;
import com.info33.platform.system.dic.service.SysDicModService;
import com.info33.platform.system.dic.vo.SysDicModVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统 - 字典 v2 模块管理
 *
 * @author nyj2one
 * @since 2022-11-30 15:15:11
 */
@Service
@RequiredArgsConstructor
public class SysDicModServiceImpl extends ServiceImpl<SysDicModDao, SysDicMod> implements SysDicModService {

    private final SysDicModDao sysDicModDao;

    /**
     * 根据数据源生成树型结构
     *
     * @param id   父 id
     * @param list 数据源
     * @return 树型结构
     */
    private List<SysDicModVO> generateTreeList(Long id, List<SysDicModVO> list) {
        List<SysDicModVO> collect = list
                .stream()
                .filter(l -> l.getPid().equals(id))
                .collect(Collectors.toList());
        collect
                .stream()
                .parallel()
                .forEach(l -> l.setChildren(generateTreeList(l.getId(), list)));
        return ObjectUtils.isEmpty(collect) ? null : collect;
    }

    @Override
    public IPage<SysDicModVO> pcPage(Page<SysDicMod> page, SysDicModDTO dto) {
        return sysDicModDao.pcPage(page, dto);
    }

    @Override
    public SysDicModVO pcTreeByIndexes(String modIndex) {
        List<SysDicModVO> list = sysDicModDao.pcTreeByIndexes(modIndex);
        SysDicModVO mod = list.stream().filter(l -> l.getModIndex().equals(modIndex)).collect(Collectors.toList()).get(0);
        mod.setChildren(generateTreeList(mod.getId(), list));
        return mod;
    }

}
